package server

import (
	"fmt"
	"net/http"

	"easy-gin/configs"
	"easy-gin/routes"
	"easy-gin/utils"

	"github.com/gin-gonic/gin"
	"golang.org/x/net/http2"
)

// 配置并启动服务
func Run(httpServer *gin.Engine) {
	utils.LocalIPv4()

	// 服务配置
	// serverConfig := configs.GetServerConfig()
	serverConfig, staticdirs := configs.ReadServerConfigs()

	// gin 运行时 release debug test
	gin.SetMode(serverConfig["env"])

	httpServer = gin.Default()
	// httpServer.UseH2C = true

	//参考：https://www.jianshu.com/p/09175c17419c
	// httpServer.StaticFS("/files", http.Dir("/Users/david/Downloads/easy-gin-master/views/index/"))

	// str, _ := os.Getwd()
	// httpServer.StaticFS("/files", http.Dir(str+"/views/index/"))

	for key, value := range staticdirs {
		httpServer.StaticFS(key, http.Dir(value)) //文件夹中不能放index.html，否则访问静态路径时会自动访问index

		// fmt.Println(key)
		// fmt.Println(value)
	}

	// 配置视图
	// if "" != serverConfig["VIEWS_PATTERN"] {
	// 	httpServer.LoadHTMLGlob(serverConfig["VIEWS_PATTERN"])
	// }

	// 注册路由
	routes.RegisterRoutes(httpServer)

	// serverAddr := serverConfig["host"] + ":" + serverConfig["port"]

	//开启https时可使用协程开启http服务
	go func() {
		if err := httpServer.Run(":" + serverConfig["port"]); err != nil {
			fmt.Print("run http server failed: %v\n", err)
		}
	}()
	fmt.Println("\n\n request info: http://" + utils.Ip + ":" + serverConfig["port"])

	fmt.Println("\n\n request info: https://" + utils.Ip + ":" + serverConfig["httpsPort"] + "\n\n")

	// 配置HTTP/2
	server := &http.Server{
		Addr:    ":" + serverConfig["httpsPort"],
		Handler: httpServer,
	}
	http2.ConfigureServer(server, &http2.Server{})

	// 启动服务器
	server.ListenAndServeTLS("server.crt", "server.key")

	// // 启动服务
	// err := httpServer.Run(serverAddr)

	// if nil != err {
	// 	panic("server run error: " + err.Error())
	// }
}
